package com.woniuxy.controller;


import com.woniuxy.commons.model.Result;
import com.woniuxy.commons.utils.DateUtil;
import com.woniuxy.commons.utils.OssTemplate;
import com.woniuxy.dao.model.StoreAttachment;
import com.woniuxy.service.StoreAttachmentService;
import com.woniuxy.service.dto.UserDetailsDto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * <p>
 * 商铺附件表 前端控制器
 * </p>
 *
 * @author psy
 * @since 2022-06-28
 */
@RestController
@RequestMapping("/storeAttachment")
@Api(tags = "商家注册时上传文件操作接口")
public class StoreAttachmentController {

    @Autowired
    private StoreAttachmentService attachmentService;

    /**
     * 商家注册(认证)时上传图片的接口
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    @ApiOperation("上传图片接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "storeId",value = "商家id")
    })
    public Result fileUp(MultipartFile file) throws IOException {

        String oldName = file.getOriginalFilename();
        String preFix = oldName.substring(oldName.lastIndexOf("."));
        String newName = System.currentTimeMillis()+preFix;
        String url = OssTemplate.fileUpload("store/"+newName,file.getInputStream(),"woniu-75-3");

        if(url != null){
            //1.将上传的图片保存到数据库商铺附件表里
            UserDetailsDto userDetailsDto = (UserDetailsDto) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            Long storeId = userDetailsDto.getId();
            StoreAttachment storeAttachment = new StoreAttachment();
            Long time = System.currentTimeMillis();
            storeAttachment.setCreateDate(DateUtil.parseDateLong(time,"yyyy-MM-dd HH:mm:ss"));
            storeAttachment.setOldFileName(oldName);
            storeAttachment.setFileName(newName);
            storeAttachment.setFileSuffix(preFix);
            storeAttachment.setFilePath(url);
            storeAttachment.setSize(file.getSize());
            storeAttachment.setStoreId(storeId);

            attachmentService.save(storeAttachment);
            //2.返回url
            return Result.success(200,"上传文件成功",url);
        }
        return Result.fail(500,"上传失败");
    }

}

